//modbus数据处理工具
package modbus

import (
	"got/funcs"
)

//编译采集命令
func Compile(addr, code int8, start, length int16) []byte {
	data := []byte{}
	data = append(data, funcs.NumberToByte(addr)...)
	data = append(data, funcs.NumberToByte(code)...)
	data = append(data, funcs.NumberToByte(start)...)
	data = append(data, funcs.NumberToByte(length)...)
	data = append(data, CRC(data)...)
	return data
}

//编译byte类型
func CompileByte(bt []byte) []byte {
	return append(bt, CRC(bt)...)
}

//modbus结构体
type ModBus struct {
	Addr     int8   //从机地址
	Code     int8   //功能码
	Length   int8   //数据长度
	Data     []byte //数据
	CRC      []byte //crc校验
	FullData []byte //接收的全部数据
}

//crc校验码
func CRC(data []byte) []byte {
	var crc16 uint16 = 0xffff
	l := len(data)
	for i := 0; i < l; i++ {
		crc16 ^= uint16(data[i])
		for j := 0; j < 8; j++ {
			if crc16&0x0001 > 0 {
				crc16 = (crc16 >> 1) ^ 0xA001
			} else {
				crc16 >>= 1
			}
		}
	}
	packet := make([]byte, 2)
	packet[0] = byte(crc16 & 0xff)
	packet[1] = byte(crc16 >> 8)
	return packet
}
